package com.funcourse.demo.sms.vcode;

import com.funcourse.demo.sms.vcode.repo.VerifyCodeRepo;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

@Service
public class VerifyCodeManager {

  @Autowired
  VerifyCodeGenerator verifyCodeGenerator;

  @Autowired
  VerifyCodeRepo verifyCodeRepo;

  public VerifyCodeMongoBean allocateVerifyCode(String ident,
      VerifyCodeFunction verifyCodeFunction) {
    verifyCodeRepo
        .deleteByIdentAndFunction(ident, verifyCodeFunction);
    return generateNewVerifyCodeMongoBean(ident, verifyCodeFunction);
  }

  private VerifyCodeMongoBean generateNewVerifyCodeMongoBean(String ident,
      VerifyCodeFunction verifyCodeFunction) {
    String verifyCode = verifyCodeGenerator
        .generateVerifyCode(verifyCodeFunction.toString(), ident);
    VerifyCodeMongoBean verifyCodeMongoBean = new VerifyCodeMongoBean();
    verifyCodeMongoBean.setFunction(verifyCodeFunction);
    verifyCodeMongoBean.setExpireTime(getExpiredTime());
    verifyCodeMongoBean.setIdent(ident);
    verifyCodeMongoBean.setVerifyCode(verifyCode);
    verifyCodeRepo.save(verifyCodeMongoBean);
    return verifyCodeMongoBean;
  }

  private long getExpiredTime() {
    return System.currentTimeMillis() + 5 * 60 * 1000;
  }

  public VerifyCodeMongoBean doVerifyCode(String ident, VerifyCodeFunction verifyCodeFunction,
      String verifyCode) {
    List<VerifyCodeMongoBean> verifyCodes = verifyCodeRepo
        .findByIdentAndVerifyCodeAndFunction(ident, verifyCode, verifyCodeFunction);
    if(CollectionUtils.isEmpty(verifyCodes)){
      return null;
    }
    VerifyCodeMongoBean result = null;
    for (VerifyCodeMongoBean verifyCodeMongoBean : verifyCodes) {
      if (!verifyCodeMongoBean.expired()) {
        result = verifyCodeMongoBean;
        break;
      }
    }
    verifyCodeRepo.deleteAll(verifyCodes);
    return result;
  }


}
